
const Controller = require('./base_controller')
const rule = {
  name: 'string',
  alias: 'string',
  comment: 'string?'
}
class ServeController extends Controller {

  //查询
  async index (ctx) {
    try {
      let serveList = await ctx.service.serviceService.index()
      this.success({data: serveList.rows})
    } catch (e) {
      this.error({
        msg: '查询失败!',
        data: e
      })
    }
  }
  //创建
  async create (ctx) {
    let { request: { body } } = ctx
    try {
      ctx.validate(rule)
      await ctx.service.serviceService.create(body)
      this.success({
        msg: '创建成功!',
        data: body
      })
    } catch (e) {
      let msg = (e && e.invalid_param) 
        ? '参数错误!' : '创建失败!'
      this.error({
        msg: msg,
        data: e
      })
    }
  }
  //修改
  async update (ctx) {
    let { params, request } = ctx
    try {
      ctx.validate(rule)
      let serve = Object.assign(params, request.body)
      await ctx.service.serviceService.update(serve)
      this.success({
        msg: '修改成功!',
        data: serve
      })
    } catch (e) {
      let msg = (e && e.invalid_param)
        ? '参数错误!' : '修改失败!'
      this.error({
        msg: msg,
        data: e
      })
    }
  }
  //删除
  async delete (ctx) {
    let { params: { id } } = ctx
    try {
      await ctx.service.serviceService.delete(id)
      this.success({
        data: { id }
      })
    } catch (e) {
      this.error({
        msg: '删除失败!',
        data: e
      })
    }
  }
}


module.exports = ServeController
